package com.kmproject.haifu.mvp.ui.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.StringUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.flyco.roundview.RoundTextView;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.http.imageloader.glide.ImageConfigImpl;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.DataHelper;
import com.jess.arms.widget.alertview.AlertView;
import com.jess.arms.widget.alertview.AlertViewOnItemClickListener;
import com.kmproject.haifu.R;
import com.kmproject.haifu.app.AppConstant;
import com.kmproject.haifu.app.utils.AppUtil;
import com.kmproject.haifu.app.utils.CustomGridItemDecoration;
import com.kmproject.haifu.app.utils.ViewExtensionKt;
import com.kmproject.haifu.di.component.DaggerHomeNewsDetailComponent;
import com.kmproject.haifu.mvp.contract.HomeNewsDetailContract;
import com.kmproject.haifu.mvp.model.entity.beans.CommentListBean;
import com.kmproject.haifu.mvp.model.entity.beans.HomeNewsBean;
import com.kmproject.haifu.mvp.model.entity.beans.UserBean;
import com.kmproject.haifu.mvp.model.entity.resbean.ReqParamsAddComment;
import com.kmproject.haifu.mvp.model.entity.resbean.ReqParamsGetCommentList;
import com.kmproject.haifu.mvp.presenter.HomeNewsDetailPresenter;
import com.kmproject.haifu.mvp.ui.widget.pullRefresh.OnRefreshLoadMoreListener2;
import com.kmproject.haifu.mvp.ui.widget.pullRefresh.PullToRefreshView;
import com.like.LikeButton;
import com.like.OnLikeListener;
import com.scwang.smartrefresh.layout.api.RefreshLayout;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import butterknife.OnClick;

import static com.jess.arms.utils.Preconditions.checkNotNull;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 08/24/2019 13:46
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
public class HomeNewsDetailActivity extends BaseActivity<HomeNewsDetailPresenter> implements HomeNewsDetailContract.View {
    @BindView(R.id.rl_root_layout)
    RelativeLayout rl_root_layout;
    @BindView(R.id.back_right_icon)
    ImageView back_right_icon;
    @BindView(R.id.tv_news_summary)
    TextView tv_news_summary;
    @BindView(R.id.tv_news_view_count)
    TextView tv_news_view_count;
    @BindView(R.id.tv_news_release_time)
    TextView tv_news_release_time;
    @BindView(R.id.wv_detail)
    WebView wv_detail;
    @BindView(R.id.srl_home_comment)
    PullToRefreshView srl_home_comment;
    @BindView(R.id.rv_home_comment)
    RecyclerView rv_home_comment;
    @BindView(R.id.i_empty)
    View empty;
    @BindView(R.id.fl_news_detail_bottom)
    FrameLayout ll_news_detail_bottom;
    @BindView(R.id.ll_comment_layout)
    LinearLayout ll_comment_layout;
    @BindView(R.id.rtv_write_comment)
    RoundTextView rtv_write_comment;
    @BindView(R.id.ll_input_comment_layout)
    LinearLayout ll_input_comment_layout;
    @BindView(R.id.et_write_comment)
    EditText et_write_comment;
    @BindView(R.id.tv_release)
    TextView tv_release;
    @BindView(R.id.tv_total_count)
    TextView tv_total_count;

    private ReqParamsGetCommentList reqParamsGetCommentList;
    private BaseQuickAdapter<CommentListBean, BaseViewHolder> adapter;
    private ReqParamsAddComment paramsAddComment;
    private HomeNewsBean mHomeNewsBean;

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerHomeNewsDetailComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_home_news_detail; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        Intent intent = getIntent();
        if (intent != null) {
            mHomeNewsBean = intent.getParcelableExtra("homeNewsBean");
        }

        if (mHomeNewsBean == null) {
            killMyself();
        }

        initWebView();
        initCommentListView();

        setWvDetail(mHomeNewsBean);

        paramsAddComment = new ReqParamsAddComment();
        paramsAddComment.setCommentType(5);
        paramsAddComment.setCommentTableId(mHomeNewsBean.getHeadlineId());

        reqParamsGetCommentList = new ReqParamsGetCommentList();
        reqParamsGetCommentList.setCommentType(5);
        reqParamsGetCommentList.setCommentTableId(mHomeNewsBean.getHeadlineId());

        getBisData();
        setTitle("海服头条");
        back_right_icon.setVisibility(View.VISIBLE);
        back_right_icon.setImageResource(R.drawable.icon_share);
    }

    @OnClick({R.id.rtv_write_comment, R.id.tv_release, R.id.back_right_icon})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rtv_write_comment:
                // todo 显示评论输入框
                showInputCommentView(true, null);
                break;
            case R.id.tv_release:
                // todo 发布
                if (StringUtils.isTrimEmpty(et_write_comment.getText().toString())) {
                    showMessage("请输入评论");
                    return;
                }
                paramsAddComment.setCommentDetail(et_write_comment.getText().toString());
                assert mPresenter != null;
                mPresenter.addComment(paramsAddComment);
                break;
            case R.id.back_right_icon:
                // todo 分享
                showMessage("分享");
                AppUtil.sharePopuWindow(HomeNewsDetailActivity.this, rl_root_layout);
                break;

        }
    }

    private void showInputCommentView(boolean isShow, String hintText) {
        if (isShow) {
            ll_comment_layout.setVisibility(View.GONE);
            ll_input_comment_layout.setVisibility(View.VISIBLE);
            if (StringUtils.isTrimEmpty(hintText)) {
                et_write_comment.setHint("请输入评论");
            } else {
                et_write_comment.setHint(hintText);
            }
            et_write_comment.requestFocus();
            KeyboardUtils.showSoftInput(et_write_comment);
            KeyboardUtils.clickBlankArea2HideSoftInput();
        } else {
            ll_comment_layout.setVisibility(View.VISIBLE);
            ll_input_comment_layout.setVisibility(View.GONE);
            KeyboardUtils.hideSoftInput(et_write_comment);
        }
    }

    @SuppressLint("SetJavaScriptEnabled")
    private void initWebView() {
        WebSettings settings = wv_detail.getSettings();
        settings.setJavaScriptEnabled(true);//支持js
        settings.setUseWideViewPort(true);//将图片调整到适合webview的大小
        settings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
        settings.setSupportZoom(true);//支持缩放，默认为true。是下面那个的前提。
        settings.setBuiltInZoomControls(false);//设置内置的缩放控件。若为false，则该WebView不可缩放
        settings.setDisplayZoomControls(false); //隐藏原生的缩放控件
        settings.setJavaScriptCanOpenWindowsAutomatically(true);//支持通过JS打开新窗口
        settings.setLoadsImagesAutomatically(true);  //支持自动加载图片
        settings.setDefaultTextEncodingName("utf-8");//设置编码格式
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL); //支持内容重新布局
        settings.setDomStorageEnabled(true); // 开启 DOM storage API 功能
        settings.setDatabaseEnabled(true);   //开启 database storage API 功能
        settings.setAppCacheEnabled(true);//开启 Application Caches 功能
        settings.setAppCacheMaxSize((5 * 1024 * 1024)); // 5MB
        settings.setGeolocationEnabled(true);//启用地理定位
//        //设置定位的数据库路径
//        val dir = context.applicationContext.getDir("database", Context.MODE_PRIVATE).path
//        settings.setGeolocationDatabasePath(dir)
        if (NetworkUtils.isConnected()) {
            settings.setCacheMode(WebSettings.LOAD_DEFAULT);
        } else {
            settings.setCacheMode(WebSettings.LOAD_CACHE_ONLY);
        }
    }

    private void setWvDetail(HomeNewsBean detail) {
        wv_detail.getSettings().setDefaultFontSize(15);
        wv_detail.getSettings().setUseWideViewPort(true); //将图片调整到适合webview的大小
        wv_detail.loadDataWithBaseURL(null, detail.getHeadlineContent(), "text/html", "utf-8", null);

        tv_news_summary.setText(detail.getHeadlineTitle());
        tv_news_view_count.setText(detail.getViewCount());
        tv_news_release_time.setText(detail.getPublishTime());
        tv_total_count.setText(String.valueOf(detail.getCommentCount()));
    }

    private void initCommentListView() {
        rv_home_comment.addItemDecoration(new CustomGridItemDecoration.Builder(Objects.requireNonNull(this)).setVerticalSpan(0f).
                setHorizontalSpan(1f).setColor(ContextCompat.getColor(this, R.color.white)).setShowLastLine(true).build());
        ArmsUtils.configRecyclerView(rv_home_comment, new LinearLayoutManager(this));
        rv_home_comment.setItemAnimator(new DefaultItemAnimator());
        srl_home_comment.setEnableRefresh(true);
        srl_home_comment.setEnableAutoLoadMore(false);
        srl_home_comment.setEnableHeaderTranslationContent(true);
//
        adapter = new BaseQuickAdapter<CommentListBean, BaseViewHolder>(R.layout.item_comment_list, new ArrayList<>()) {
            @Override
            protected void convert(BaseViewHolder helper, CommentListBean item) {
                getMglideImage().loadImage(HomeNewsDetailActivity.this, ImageConfigImpl.builder().url(item.getUserInfo().getAvatar())
                        .imageView(helper.getView(R.id.imv_user_head_portrait))
                        .build());
                helper.setText(R.id.tv_user_name, item.getUserInfo().getNickName());
                getMglideImage().loadImage(HomeNewsDetailActivity.this, ImageConfigImpl.builder().url(item.getUserInfo().getLevelHeadImage())
                        .imageView(helper.getView(R.id.imv_level_icon))
                        .build());
                LikeButton likeButton = helper.getView(R.id.lb_like);
                if (item.getLiked() == 1) {
                    likeButton.setLiked(true);
                } else {
                    likeButton.setLiked(false);
                }
                helper.setText(R.id.tv_like_count, String.valueOf(item.getLikeCount()));
                helper.setText(R.id.tv_comment_content, item.getCommentDetail());
                helper.setText(R.id.tv_time, item.getPublishTime());
                UserBean userBean = DataHelper.getDeviceData(HomeNewsDetailActivity.this, AppConstant.USER_INFO);
                TextView tv_delete = helper.getView(R.id.tv_delete);
                tv_delete.setTag(item.getUserCommentId());
                if (userBean != null && !userBean.getUserId().isEmpty() && userBean.getUserId().equals(String.valueOf(item.getUserId()))) {
                    tv_delete.setVisibility(View.VISIBLE);
                    long tag = (long) tv_delete.getTag();
                    tv_delete.setOnClickListener(v -> {
                        new AlertView(getString(R.string.note), "确定删除改评论吗？", getString(R.string.cancel), new String[]{getString(R.string.sure_delete)}, null, HomeNewsDetailActivity.this, AlertView.Style.Alert, new AlertViewOnItemClickListener() {

                            @Override
                            public void onItemClick(Object o, int position) {
                                if (position != AlertView.CANCELPOSITION) {
                                    showLoading();
                                    assert mPresenter != null;
                                    mPresenter.deleteComment(String.valueOf(tag));
                                }
                            }
                        }).show();
                    });
                } else {
                    tv_delete.setVisibility(View.GONE);
                }
                likeButton.setTag(helper.getAdapterPosition());
                likeButton.setOnLikeListener(new OnLikeListener() {
                    @Override
                    public void liked(LikeButton likeButton) {
                        int tag2 = (int) likeButton.getTag();
                        CommentListBean bean = adapter.getItem(tag2);
                        assert mPresenter != null;
                        assert bean != null;
                        mPresenter.likeComment(String.valueOf(bean.getUserCommentId()));
                    }

                    @Override
                    public void unLiked(LikeButton likeButton) {
                        int tag2 = (int) likeButton.getTag();
                        CommentListBean bean = adapter.getItem(tag2);
                        assert mPresenter != null;
                        assert bean != null;
                        mPresenter.cancelComment(String.valueOf(bean.getUserCommentId()));
                    }
                });
//
//                if (item.getChildren()!=null&&item.getChildren().size()>0){
//                    BaseQuickAdapter<CommentListBean, BaseViewHolder> towLevelladapter = ;
//                }
            }
        };
        rv_home_comment.setAdapter(adapter);

        adapter.setOnItemClickListener((adapter, view, position) -> {
            // todo 暂时屏蔽，只能回复文章
//            CommentListBean bean = (CommentListBean) adapter.getItem(position);
//            assert bean != null;
//            showInputCommentView(true, "回复：" + bean.getUserInfo().getNickName());
//            paramsAddComment.setParentId(bean.getCommentTableId());
        });

        srl_home_comment.setOnRefreshLoadMoreListener2(new OnRefreshLoadMoreListener2() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout, int curPageNo) {
                // 加载更多
                reqParamsGetCommentList.setPage(curPageNo);
                getBisData();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout, int curPageNo) {
                // 刷新
                reqParamsGetCommentList.setPage(curPageNo);
                getBisData();
            }
        });
//        HandleWindowSoftInputBug.assistActivity(this);
    }

    private void getBisData() {
        assert mPresenter != null;
        mPresenter.getCommentList(reqParamsGetCommentList);
    }

    private void getDetail() {
        assert mPresenter != null;
        mPresenter.getHomeNewsDetail(String.valueOf(mHomeNewsBean.getHeadlineId()));
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @Override
    public void getHomeNewsDetailSuccess(HomeNewsBean newsBean) {
        if (newsBean != null) {
            mHomeNewsBean = newsBean;
            setWvDetail(mHomeNewsBean);
        }
    }

    @Override
    public void addCommentSuccess() {
        getDetail();
        getBisData();
        et_write_comment.setText(null);
        showInputCommentView(false, null);
        paramsAddComment.setParentId(0);
    }

    @Override
    public void cancelCommentSuccess() {
        getDetail();
        getBisData();
    }

    @Override
    public void likeCommentSuccess() {
        getDetail();
        getBisData();
    }

    @Override
    public void getCommentListSuccess(List<CommentListBean> commentListBeans) {
        srl_home_comment.finishLoadMore();
        srl_home_comment.finishRefresh();
        if (commentListBeans != null && !commentListBeans.isEmpty()) {
            ViewExtensionKt.visible(empty, false);
            ViewExtensionKt.visible(rv_home_comment, true);
            if (ViewExtensionKt.isPullDown(srl_home_comment, commentListBeans.size(), reqParamsGetCommentList.getLimit())) {
                adapter.setNewData(commentListBeans);
            } else {
                adapter.addData(commentListBeans);
            }
        } else {
            if (reqParamsGetCommentList.getPage() > 1) {
                ViewExtensionKt.visible(empty, false);
                ViewExtensionKt.visible(rv_home_comment, true);
            } else {
                ViewExtensionKt.visible(empty, true);
                ViewExtensionKt.visible(rv_home_comment, false);
            }
        }
    }

    @Override
    public void getCommentListFail() {
        srl_home_comment.finishLoadMore();
        srl_home_comment.finishRefresh();
        if (reqParamsGetCommentList.getPage() > 1) {
            reqParamsGetCommentList.setPage(reqParamsGetCommentList.getPage() - 1);
        }
    }

    @Override
    public void deleteCommentSuccess() {
        getDetail();
        getBisData();
    }

    @Override
    public void onResume() {
        super.onResume();
        wv_detail.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        wv_detail.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (wv_detail != null) {
            wv_detail.clearHistory();
//            (web_view.getParent()).removeView(web_view)
            wv_detail.loadUrl("about:blank");
            wv_detail.stopLoading();
            wv_detail.destroy();
        }
    }
}
